import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterOutlet } from '@angular/router';
import { ButtonModule } from 'ng-devui/button';
import { DataTableModule } from 'ng-devui/data-table';
import { ModalModule, DialogService } from 'ng-devui/modal';
import { FormModule } from 'ng-devui/form';
import { InputNumberModule } from 'ng-devui/input-number';
import { SelectModule } from 'ng-devui/select';
import { ToastModule, ToastService } from 'ng-devui/toast';
import { LayoutModule } from 'ng-devui/layout';
import { DropDownModule } from 'ng-devui/dropdown';
import { Product, ProductFormData } from './models/product.model';
import { ProductService } from './services/product.service';
import { I18nService, Language } from './services/i18n.service';
import { AiService } from './services/ai.service';
import { AiAssistantComponent } from './components/ai-assistant/ai-assistant.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    RouterOutlet,
    ButtonModule,
    DataTableModule,
    ModalModule,
    FormModule,
    InputNumberModule,
    SelectModule,
    ToastModule,
    LayoutModule,
    DropDownModule,
    AiAssistantComponent
  ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent implements OnInit {
  products: Product[] = [];
  filteredProducts: Product[] = [];
  searchText = '';
  showProductModal = false;
  
  // Form data
  isEditMode = false;
  editingProductId: number | null = null;
  productForm: ProductFormData = {
    name: '',
    category: '',
    price: 0,
    stock: 0,
    description: '',
    status: 'active'
  };

  // Categories for dropdown
  categories = [
    { label: '电子产品', value: '电子产品' },
    { label: '配件', value: '配件' },
    { label: '服装', value: '服装' },
    { label: '食品', value: '食品' },
    { label: '图书', value: '图书' }
  ];

  statusOptions = [
    { label: '上架', value: 'active' },
    { label: '下架', value: 'inactive' }
  ];

  // Language options
  languages: Array<{ label: string; value: Language }> = [
    { label: '简体中文', value: 'zh-CN' },
    { label: 'English', value: 'en-US' }
  ];
  currentLanguage: Language = 'zh-CN';

  constructor(
    private productService: ProductService,
    private dialogService: DialogService,
    private toastService: ToastService,
    public i18n: I18nService
  ) {}

  ngOnInit(): void {
    this.productService.getProducts().subscribe(products => {
      this.products = products;
      this.filteredProducts = products;
    });

    this.i18n.currentLang$.subscribe(lang => {
      this.currentLanguage = lang;
      this.updateCategoryLabels();
      this.updateStatusLabels();
    });
  }

  updateCategoryLabels(): void {
    if (this.currentLanguage === 'en-US') {
      this.categories = [
        { label: 'Electronics', value: '电子产品' },
        { label: 'Accessories', value: '配件' },
        { label: 'Clothing', value: '服装' },
        { label: 'Food', value: '食品' },
        { label: 'Books', value: '图书' }
      ];
    } else {
      this.categories = [
        { label: '电子产品', value: '电子产品' },
        { label: '配件', value: '配件' },
        { label: '服装', value: '服装' },
        { label: '食品', value: '食品' },
        { label: '图书', value: '图书' }
      ];
    }
  }

  updateStatusLabels(): void {
    this.statusOptions = [
      { label: this.i18n.t('product.active'), value: 'active' },
      { label: this.i18n.t('product.inactive'), value: 'inactive' }
    ];
  }

  onSearch(): void {
    if (!this.searchText.trim()) {
      this.filteredProducts = this.products;
    } else {
      this.filteredProducts = this.products.filter(p =>
        p.name.toLowerCase().includes(this.searchText.toLowerCase()) ||
        p.category.toLowerCase().includes(this.searchText.toLowerCase())
      );
    }
  }

  openAddModal(): void {
    this.isEditMode = false;
    this.editingProductId = null;
    this.resetForm();
    this.showProductModal = true;
  }

  openEditModal(product: Product): void {
    this.isEditMode = true;
    this.editingProductId = product.id;
    this.productForm = {
      name: product.name,
      category: product.category,
      price: product.price,
      stock: product.stock,
      description: product.description,
      status: product.status
    };
    this.showProductModal = true;
  }

  deleteProduct(product: Product): void {
    const results = this.dialogService.open({
      id: 'delete-dialog',
      width: '400px',
      showAnimate: true,
      title: this.i18n.t('product.delete'),
      content: this.i18n.t('product.deleteConfirm'),
      backdropCloseable: true,
      dialogtype: 'warning',
      buttons: [
        {
          cssClass: 'primary',
          text: this.i18n.t('common.ok'),
          handler: () => {
            this.productService.deleteProduct(product.id);
            this.toastService.open({
              value: [{ severity: 'success', summary: this.i18n.t('message.deleteSuccess') }]
            });
            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: this.i18n.t('common.cancel'),
          handler: () => {
            results.modalInstance.hide();
          }
        }
      ]
    });
  }

  submitForm(): void {
    if (!this.validateForm()) {
      this.toastService.open({
        value: [{ severity: 'error', summary: this.i18n.t('form.required') }]
      });
      return;
    }

    if (this.isEditMode && this.editingProductId !== null) {
      this.productService.updateProduct(this.editingProductId, this.productForm);
      this.toastService.open({
        value: [{ severity: 'success', summary: this.i18n.t('message.editSuccess') }]
      });
    } else {
      this.productService.addProduct(this.productForm);
      this.toastService.open({
        value: [{ severity: 'success', summary: this.i18n.t('message.addSuccess') }]
      });
    }
    this.closeModal();
  }

  validateForm(): boolean {
    return !!(this.productForm.name && 
             this.productForm.category && 
             this.productForm.price > 0 && 
             this.productForm.stock >= 0);
  }

  resetForm(): void {
    this.productForm = {
      name: '',
      category: '',
      price: 0,
      stock: 0,
      description: '',
      status: 'active'
    };
  }

  closeModal(): void {
    this.showProductModal = false;
    this.resetForm();
  }

  changeLanguage(lang: Language): void {
    this.i18n.setLanguage(lang);
  }

  getStatusLabel(status: string): string {
    return status === 'active' ? this.i18n.t('product.active') : this.i18n.t('product.inactive');
  }
}
